package repository

import (
	"context"
	"elegantGo/chapter17/oo"
	"elegantGo/chapter17/repository/ent"
	"elegantGo/chapter17/repository/ent/user"
)

type User struct {
	db *ent.Client
}

func NewUser(db *ent.Client) *User {
	repo := new(User)
	repo.db = db
	return repo
}

func (repo *User) Fetch(ctx context.Context, id int) oo.User {
	return repo.FetchOne(ctx, func(opt *ent.UserQuery) {
		opt.Where(user.ID(id))
	})
}

func (repo *User) FetchOne(ctx context.Context, optionFunc func(opt *ent.UserQuery)) oo.User {
	builder := repo.db.User.Query()
	optionFunc(builder)
	return builder.FirstX(ctx).Mapper()
}

func (repo *User) FetchMany(ctx context.Context, optionFunc func(opt *ent.UserQuery)) oo.Users {
	builder := repo.db.User.Query()
	optionFunc(builder)
	var entUsers ent.Users = builder.AllX(ctx)
	return entUsers.Mapper()
}
